<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Amqp\Result;
use PhpAmqpLib\Message\AMQPMessage;
use Hyperf\Amqp\Message\Type;
use App\Model\PssLogModel\MicroServiceLog;
use Service\AppService\IdService;


/**
 * qos (prefetch_size,prefetch_count,global)
 * 写入日志micro_service_hyperf_log
 * @Consumer(exchange="YUNCANG_MICRO_HYPERF_LOG_MESSAGE", routingKey="YUNCANG_MICRO_HYPERF_LOG_MESSAGE", queue="YUNCANG_MICRO_HYPERF_LOG_MESSAGE", nums=1)
 */
class MicroServiceHyperfLogMessageConsumer extends ConsumerMessage
{
    protected $type = Type::DIRECT;//直连模式
    protected $qos  = [
        'prefetch_count'    => 10
    ];

    public function consumeMessage($data, AMQPMessage $message): string
    {
        try {
            if( empty($data['id']) ) {
                $data['id'] = IdService::instance()->getLogID();
            }
            
            if( empty($data['cd']) ) {
                $data['cd'] = time();
            }
            
            $data['request_param'] = is_array($data['request_param']) ? json_encode($data['request_param'],JSON_UNESCAPED_UNICODE) : $data['request_param'];
            //写入数据
            $insert = [
                'id'                => $data['id'],
                'interface_code'    => $data['interface_code'] ?? '',
                'request_url'       => $data['request_url'] ?? '',
                'request_param'     => $data['request_param'] ?? '',
                'response_code'     => $data['response_code'] ?? '',
                'response_data'     => $data['response_data'] ?? '',
                'req_used_time'     => $data['req_used_time'] ?? '',
                'cd'                => $data['cd'],
            ];
            MicroServiceLog::instance()->add($insert);
            return Result::ACK;
        } catch ( \Throwable $t ) {
            echo $t->getMessage().PHP_EOL;
            logger('error','MicroServiceHyperfLogMessageConsumer')->info($t->getMessage());
            sleep(3);//休眠3秒之后，重回队列
            return Result::REQUEUE;
        }
    }
    
    /**
     * 设置是否自启动
     */
    public function isEnable() : bool
    {
        $isDisAable = env('AMQP_YUNCANG_MICRO_HYPERF_LOG_MESSAGE_DISABLE');
        return $isDisAable ? false : true ;
    }
}